package cn.enjoyedu.nettyhttp.sever2;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;


import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;

public class HttpServer {
    public static final int port = 6677; //设置服务端口
    private static EventLoopGroup group = new NioEventLoopGroup(); //通过NIo方式来接收处理链接
    private static ServerBootstrap b = new ServerBootstrap();
    private static final Boolean SSL = false; //是否开启SSL模式

    /**
     * Netty创建全部都是实现AbstractBootStrap,
     * 客户端的是BootStrap，服务端的则是ServerBootStrap
     */
    public static void main(String[] args) throws CertificateException, SSLException, InterruptedException {
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }
        try {
            b.group(group);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ServerHandlerInit(sslCtx));//设置过滤器
            //服务绑定监听端口
            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务端启动成功，端口是：" + port);
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();//关闭EvenLoopGroup.释放所有资源创建的线程
        }

    }
}
